package org.paysim.payment.service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.paysim.annotation.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class PaymentStrategyFactory {
    private static final Logger logger = LoggerFactory.getLogger(PaymentStrategyFactory.class);

    private final Map<String, IPaymentService> strategyMap;

    // 通过构造器自动收集所有策略Bean
    // @Autowired
    public PaymentStrategyFactory(List<IPaymentService> strategies) {
        strategyMap = strategies.stream().collect(Collectors
                .toMap(strategy -> strategy.getClass().getAnnotation(Channel.class).value(), Function.identity()));
        logger.info("paymentStrategy has : {}", strategyMap.size());
    }

    public IPaymentService getStrategy(String channel) {
        return Optional.ofNullable(strategyMap.get(channel))
                .orElseThrow(() -> new IllegalArgumentException("Unsupported channel: " + channel));
    }
}
